import { LinkOutlined, FullscreenOutlined, FullscreenExitOutlined, RedoOutlined, LoadingOutlined, LockOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max';
import { history, useLocation } from '@umijs/max';
import React, { useState, useEffect, useCallback } from 'react';
import { AvatarDropdown, AvatarName, Footer, Question, SelectLang } from '@/components';
import { currentUser as queryCurrentUser } from '@/services/ant-design-pro/api';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import '@ant-design/v5-patch-for-react-19';
import routes from '../config/routes';
import { Breadcrumb } from 'antd';

// 环境常量
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
const lockPath = '/lock'; // 锁屏页面路由
// 不需要面包屑的页面路径集合
const noBreadcrumbPaths = [loginPath, '/user/register', '/user/register-result', lockPath];

/**
 * 登录状态检查
 * @returns boolean - 是否已登录
 */
const checkLoginStatus = (): boolean => {
  const voucher = sessionStorage.getItem('voucher');
  const isLoggedIn = voucher === 'Login-credentials';
  // 如果未登录，清空所有存储
  if (!isLoggedIn) {
    sessionStorage.clear();
    localStorage.clear();
  }
  return isLoggedIn;
};

/**
 * 锁屏状态检查
 * @returns boolean - 是否已锁屏
 */
const checkLockStatus = (): boolean => {
  return localStorage.getItem('isLocked') === 'true';
};

/**
 * 全屏控制 Hook
 * @returns { isFullscreen: boolean, toggleFullscreen: () => void } - 全屏状态和切换方法
 */
const useFullscreen = () => {
  const [isFullscreen, setIsFullscreen] = useState(false);
  // 检查当前是否处于全屏状态
  const checkFullscreen = useCallback(() => {
    setIsFullscreen(
      !!(document as any).fullscreenElement ||
      !!(document as any).webkitFullscreenElement ||
      !!(document as any).mozFullScreenElement ||
      !!(document as any).msFullscreenElement,
    );
  }, []);
  // 切换全屏状态
  const toggleFullscreen = useCallback(() => {
    if (isFullscreen) {
      // 退出全屏
      if ((document as any).exitFullscreen) (document as any).exitFullscreen();
      else if ((document as any).webkitExitFullscreen) (document as any).webkitExitFullscreen();
      else if ((document as any).mozCancelFullScreen) (document as any).mozCancelFullScreen();
      else if ((document as any).msExitFullscreen) (document as any).msExitFullscreen();
    } else {
      // 进入全屏
      const docEl = document.documentElement;
      if ((docEl as any).requestFullscreen) (docEl as any).requestFullscreen();
      else if ((docEl as any).webkitRequestFullscreen) (docEl as any).webkitRequestFullscreen();
      else if ((docEl as any).mozRequestFullScreen) (docEl as any).mozRequestFullScreen();
      else if ((docEl as any).msRequestFullscreen) (docEl as any).msRequestFullscreen();
    }
  }, [isFullscreen]);
  // 监听全屏状态变化
  useEffect(() => {
    const fullscreenChangeHandler = () => checkFullscreen();
    document.addEventListener('fullscreenchange', fullscreenChangeHandler);
    document.addEventListener('webkitfullscreenchange', fullscreenChangeHandler);
    document.addEventListener('mozfullscreenchange', fullscreenChangeHandler);
    document.addEventListener('MSFullscreenChange', fullscreenChangeHandler);
    return () => {
      document.removeEventListener('fullscreenchange', fullscreenChangeHandler);
      document.removeEventListener('webkitfullscreenchange', fullscreenChangeHandler);
      document.removeEventListener('mozfullscreenchange', fullscreenChangeHandler);
      document.removeEventListener('MSFullscreenChange', fullscreenChangeHandler);
    };
  }, [checkFullscreen]);
  return { isFullscreen, toggleFullscreen };
};

/**
 * 递归遍历路由树，精准匹配当前路径
 * @param routes - 路由配置数组
 * @param currentPath - 当前页面路径
 * @returns 匹配到的路由配置，未找到返回 null
 */
const findMatchedRoute = (routes: any[], currentPath: string): any => {
  for (const route of routes) {
    if (route.path === currentPath) {
      return route;
    }
    if (route.routes && route.routes.length > 0) {
      const parentPath = route.path === '/' ? '' : route.path;
      for (const childRoute of route.routes) {
        const fullChildPath = `${parentPath}/${childRoute.path}`.replace(/\/+/g, '/');
        if (fullChildPath === currentPath) {
          return childRoute;
        }
      }
      const deepMatched = findMatchedRoute(route.routes, currentPath);
      if (deepMatched) {
        return deepMatched;
      }
    }
  }
  return null;
};

/**
 * 获取应用初始状态
 */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser({ skipErrorHandler: true });
      return msg.data;
    } catch (_error) {
      history.push(loginPath);
    }
    return undefined;
  };

  const { location } = history;

  // 1. 登录拦截：只检查 sessionStorage 中的 voucher
  if (location.pathname !== loginPath && !checkLoginStatus()) {
    sessionStorage.clear();
    localStorage.clear();
    history.push(loginPath);
    return {
      fetchUserInfo,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }

  // 2. 锁屏拦截：如果已锁屏且当前不是锁屏页，强制跳转到锁屏页
  if (checkLockStatus() && location.pathname !== lockPath) {
    localStorage.setItem('attemptedPath', location.pathname);
    history.replace(lockPath);
    return {
      fetchUserInfo,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }

  if (!noBreadcrumbPaths.includes(location.pathname)) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }

  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

/**
 * 全局路由拦截（关键修复：拦截所有路由变化）
 */
export function onRouteChange({ location, action }: {
  location: Location;
  routes: any[];
  action: 'PUSH' | 'POP' | 'REPLACE';
}) {
  // 已登录状态下才检查锁屏
  if (checkLoginStatus()) {
    const isLocked = checkLockStatus();
    const isLockPage = location.pathname === lockPath;

    // 已锁屏且目标页面不是锁屏页 → 强制跳回锁屏页
    if (isLocked && !isLockPage) {
      // 记录用户原本想访问的路径
      localStorage.setItem('attemptedPath', location.pathname);
      // 使用 replace 避免添加新路由到历史栈
      history.replace(lockPath);
      // 针对 POP 操作（返回/前进），补充覆盖历史栈
      if (action === 'POP') {
        window.history.pushState(null, '', lockPath);
      }
    }
  }
}

/**
 * 布局配置
 */
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  const { isFullscreen, toggleFullscreen } = useFullscreen();
  const [routeKey, setRouteKey] = useState(Date.now()); // 用于页面刷新的key
  const [isRefreshing, setIsRefreshing] = useState(false); // 刷新状态
  const location = useLocation();

  /**
   * 锁屏跳转函数（优化：记录当前路径）
   */
  const handleLockScreen = useCallback(() => {
    // 记录当前页面路径（用于解锁后跳转）
    if (location.pathname !== lockPath && location.pathname !== loginPath) {
      localStorage.setItem('attemptedPath', location.pathname);
    }
    // 设置锁屏状态
    localStorage.setItem('isLocked', 'true');
    // 跳转到锁屏页面
    history.push(lockPath);
  }, [location.pathname]);

  /**
   * 获取当前路由名称
   * @returns 路由名称，未匹配到返回"未知页面"
   */
  const getCurrentRouteName = useCallback(() => {
    const currentPath = location.pathname;
    const matchedRoute = findMatchedRoute(routes, currentPath);
    if (matchedRoute && matchedRoute.name) {
      return matchedRoute.name;
    }
    const parentPath = currentPath.split('/').slice(0, -1).join('/') || '/';
    const parentRoute = findMatchedRoute(routes, parentPath);
    if (parentRoute && parentRoute.name) {
      return parentRoute.name;
    }
    return '未知页面';
  }, [location.pathname]);

  const currentRouteName = getCurrentRouteName();

  /**
   * 刷新当前页面
   */
  const refreshPage = useCallback(() => {
    setIsRefreshing(true);
    setRouteKey(Date.now()); // 改变key触发重新渲染
    setTimeout(() => setIsRefreshing(false), 300); // 300ms后重置刷新状态
  }, []);

  /**
   * 生成面包屑数据
   * @returns 面包屑项数组
   */
  const getBreadcrumbItems = useCallback(() => {
    const currentPath = location.pathname;
    const items: any[] = [];
    if (noBreadcrumbPaths.includes(currentPath)) {
      return items;
    }
    const pathSegments = currentPath.split('/').filter(Boolean);
    let currentFullPath = '';
    pathSegments.forEach((segment) => {
      currentFullPath += `/${segment}`;
      const matchedRoute = findMatchedRoute(routes, currentFullPath);
      if (matchedRoute?.name) {
        items.push({
          title: matchedRoute.name,
          key: currentFullPath,
        });
      }
    });
    return items;
  }, [location.pathname, currentRouteName]);

  return {
    // 顶部中间区域：面包屑
    headerContentRender: () => (
      <Breadcrumb
        items={getBreadcrumbItems()}
        style={{ flex: 1, fontSize: '14px', color: 'rgba(0,0,0,0.65)', marginLeft: '20px', }} separator=">" />
    ),

    actionsRender: () => [
      // 锁屏按钮 - 新增
      <LockOutlined
        key="lock"
        onClick={handleLockScreen}
        title="锁定屏幕"
        style={{ cursor: 'pointer', marginRight: 8 }}
      />,
      isFullscreen ? (
        <FullscreenExitOutlined key="exit-fullscreen" onClick={toggleFullscreen} title="退出全屏" style={{ cursor: 'pointer', marginRight: 8 }} />
      ) : (
        <FullscreenOutlined key="fullscreen" onClick={toggleFullscreen} title="全屏显示" style={{ cursor: 'pointer', marginRight: 8 }} />
      ),
      isRefreshing ? (
        <LoadingOutlined key="refresh-loading" spin style={{ fontSize: '16px', cursor: 'pointer', marginRight: 8 }} title="刷新中..." onClick={refreshPage} />
      ) : (
        <RedoOutlined key="refresh" style={{ fontSize: '16px', cursor: 'pointer', marginRight: 8 }} title="刷新页面" onClick={refreshPage} />
      ),
    ],

    // 用户头像下拉菜单配置
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => <AvatarDropdown>{avatarChildren}</AvatarDropdown>,
    },
    // 页脚
    footerRender: () => <Footer />,
    // 页面切换时的回调（增强登录和锁屏拦截）
    onPageChange: () => {
      const { location } = history;
      // 1. 登录拦截
      if (!checkLoginStatus() && location.pathname !== loginPath) {
        history.push(loginPath);
        return;
      }

      // 2. 锁屏拦截
      if (checkLockStatus() && location.pathname !== lockPath) {
        localStorage.setItem('attemptedPath', location.pathname);
        history.replace(lockPath);
      }
    },
    // 隐藏菜单头部
    menuHeaderRender: undefined,
    // 子组件渲染（支持页面刷新）
    childrenRender: (children) => <div key={routeKey}>{children}</div>,
    // 继承初始状态中的布局配置
    ...initialState?.settings,
  };
};

/**
 * 请求配置（错误处理）
 */
export const request: RequestConfig = { ...errorConfig };